package com.wdh.dbutil;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.Properties;

public class DataSourceUtil {

    /**
     * C3P0数据源
     * */
    public static DataSource getDataSourceWithC3P0() throws PropertyVetoException {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setDriverClass("com.mysql.cj.jdbc.Driver");
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/wdh");
        ds.setUser("root");
        ds.setPassword("1234567890");
        return ds;
    }

    /**
     * 读取c3p0-config.xml中的默认的数据源配置
     * */
    public static DataSource getDefaultDateSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        return dataSource;
    }

    /**
     * 读取c3p0-config.xml中指定的数据源配置
     * */
    public static DataSource getDateSourceWithConfig(String dsName) {
        ComboPooledDataSource dataSource = new ComboPooledDataSource(dsName);
        return dataSource;
    }

    public static DataSource getDataSourceWithDBCP() {
        BasicDataSource dbcp = new BasicDataSource();
        dbcp.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dbcp.setUrl("jdbc:mysql://localhost:3306/wdh");
        dbcp.setUsername("root");
        dbcp.setPassword("1234567890");
        dbcp.setInitialSize(20);
        dbcp.setMaxActive(10);

        return dbcp;
    }

    public static DataSource getDataSourceFromProp() throws Exception {
        Properties properties = new Properties();
        InputStream input = new DataSourceUtil().getClass().getClassLoader().getResourceAsStream("db-cfg.properties");
        properties.load(input);

        DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
        return dataSource;
    }
}
